package com.ftg.midamall.admin.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ftg.midamall.admin.dto.AdminInfo;
import com.ftg.midamall.admin.dto.ModifyAdminInfo;
import com.ftg.midamall.admin.dto.UserInfo;
import com.ftg.midamall.admin.entity.UmsAdmin;
import com.ftg.midamall.admin.entity.UmsAdminRoleRelation;
import com.ftg.midamall.admin.mapper.UmsAdminMapper;
import com.ftg.midamall.admin.mapper.UmsAdminRoleMapper;
import com.ftg.midamall.admin.mapper.UmsRoleMapper;
import com.ftg.midamall.admin.service.IUmsAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.midamall.admin.vo.UmsAdminVo;
import com.ftg.midamall.comm.tool.ConventUtil;
import com.ftg.midamall.comm.tool.UserPasswordCrypto;
import com.ftg.midamall.comm.vo.CodeStatusEnum;
import com.ftg.midamall.comm.vo.ConstUtil;
import com.ftg.midamall.comm.vo.RespMessUtil;
import com.ftg.midamall.feign.UploadAvatarFeign;
import freemarker.template.utility.StringUtil;
import lombok.SneakyThrows;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static com.baomidou.mybatisplus.core.toolkit.IdWorker.getId;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author qjw
 * @since 2023-10-20
 */
@Service
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements IUmsAdminService {


    @Override
    public String upload(MultipartFile icon, Long id) {
        return null;
    }

    /**
     * 后台_用户登录功能
     *
     * @param userinfo
     * @return
     */

    @Override

    public RespMessUtil<UmsAdminVo> login(UserInfo userinfo) {


        QueryWrapper<UmsAdmin> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("username", userinfo.getUsername());


        String secretPassword = UserPasswordCrypto.md5Password(userinfo.getPassword());

        queryWrapper.eq("password", secretPassword);


        UmsAdmin umsAdmin = this.getBaseMapper().selectOne(queryWrapper);


        if (Objects.isNull(umsAdmin)) {

            return RespMessUtil.build(CodeStatusEnum.INVALID_USERNAME_PASSWORD);

        } else {

            this.getBaseMapper().updateLoginTime(umsAdmin.getId());


            UmsAdminVo umsAdminVo = ConventUtil.conventSwapClass(umsAdmin, UmsAdminVo.class);

            return RespMessUtil.build(CodeStatusEnum.SUCCESS, umsAdminVo);

        }

    }

    @Resource
    UmsAdminMapper umsAdminMapper;
    @Resource

    UmsAdminRoleMapper umsAdminRoleMapper;

    @Resource
    UmsRoleMapper roleMapper;


    /**
     * 后台_用户注册功能并分配角色
     *
     * @param u
     * @param RoleIds
     * @return
     */
    @Override
    public RespMessUtil<Integer> register(@Param("u") AdminInfo u, List<Long> RoleIds) {

        if (u.getUsername() == null || u.getUsername().equals("")) {
            throw new RuntimeException("对不起，用户名不能为空");
        }

        if (u.getPassword() == null || u.getPassword().equals("")) {

            throw new RuntimeException("对不起，密码不能为空");
        }
        if (!Objects.isNull(umsAdminMapper.selectUserName(u.getUsername()))) {

            throw new RuntimeException("用户已注册");

        } else {

            umsAdminMapper.insertAdmin(u);
        }
        Long admin_id = umsAdminRoleMapper.findAdminIdByUsername(u.getUsername());

        System.out.println(admin_id);

        for (Long role_id : RoleIds) {
            umsAdminRoleMapper.insertAdminRoleRelation(admin_id, role_id);
            roleMapper.updateAdminCount(role_id,admin_id);
        }

        return RespMessUtil.build(CodeStatusEnum.SUCCESS);

    }


    /**
     * 后台_用户删除功能
     *
     * @param id
     * @return
     */
    @Override
    public Integer deleteAdmin(int id) {
        umsAdminMapper.delAdmin(id);
        return umsAdminMapper.deleteById(id);
    }

    /**
     * 后台_用户修改功能
     *
     * @param id
     * @return
     */
    @Override
    public Integer modifyAdminPass(int id, String password) {
        return umsAdminMapper.modifyAdminPass(id, password);
    }

    /**
     * 后台_用户分页查找功能
     *
     * @param
     * @return
     */
    @Override
    public RespMessUtil<IPage> showAdminWithPage(String username, Integer status, int start, int limit) {
        IPage<UmsAdmin> ipage = new Page<>(start, limit);
        QueryWrapper<UmsAdmin> query = new QueryWrapper<>();
        if (!StrUtil.isBlank(username)) {
            query.like("username", username);
        }
        if (status != null) {
            query.like("status", status);
        }
        return RespMessUtil.build(CodeStatusEnum.SUCCESS, this.getBaseMapper().selectPage(ipage, query));
    }

    @Override
    public Integer modifyAdmin(ModifyAdminInfo u) {
        return null;
    }

    /**
     * 后台_用户添加role_id功能
     *
     * @param
     */
    @Override
    public Integer saveRole(@RequestBody UmsAdminRoleRelation u) {
        return umsAdminMapper.insertRole(u);
    }

    /**
     * 批量删除
     *
     * @param
     * @return
     */
    @Override
    public Integer deleteAllAdmin(List<Integer> id) {
        umsAdminMapper.deleteAllAdminRole(id);
        umsAdminMapper.deleteAllAdmin(id);
        return 1;
    }

    /**
     * 修改状态
     * @param id
     * @return
     */
    @Override
    public Boolean switchStatus(int id) {
        return this.getBaseMapper().switchStatus(id);
    }

    /**
     * 修改用户信息以及分配角色
     * @param ur
     * @param roleIds
     * @return
     */
    @Override
    public RespMessUtil<Integer> updateById(AdminInfo ur, List<Long> roleIds) {

        AdminInfo rename = umsAdminRoleMapper.selectByNameId(ur.getUsername(), ur.getId());
        if (!Objects.isNull(rename)) {
            throw new RuntimeException("角色名不可重复");
        }

        long admin_id = ur.getId();
        umsAdminMapper.updateById(ur, admin_id);


        for (Long role_id : roleIds) {

            roleMapper.reduceCount(role_id,admin_id);

            umsAdminRoleMapper.delAdmin(admin_id);

            umsAdminRoleMapper.insertAdminRoleRelation(admin_id, role_id);

            roleMapper.updateAdminCount(role_id,admin_id);

        }

        return RespMessUtil.build(CodeStatusEnum.SUCCESS);

    }

    /**
     * 修改用户信息
     * 图片
     * @param user 要修改的用户对象
     * @return 返回修改结果
     */
    @Override
    public RespMessUtil<Boolean> modifyUser(UmsAdmin user) {
        if (Objects.nonNull(user)) {
            // 密码加密
            if (Objects.nonNull(user.getPassword())) {
                user.setPassword(UserPasswordCrypto.md5Password(user.getPassword()));
            }
            return RespMessUtil.build(CodeStatusEnum.SUCCESS, this.getBaseMapper().modifyUmsAdminWithNonNull(user));
        }
        return RespMessUtil.build(CodeStatusEnum.FAILURE, false);
    }

    @Resource
    private UploadAvatarFeign uploadAvatarFeign;
    public static final String RESULT_AVATAR_URL = "url";

    /**
     * 上传头像
     *
     * @param id         用户id
     * @param avatarFile 头像文件
     * @return 上传结果
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public RespMessUtil<JSONObject> uploadAvatar(Long id, MultipartFile avatarFile) {

        if (Objects.nonNull(id) && Objects.nonNull(avatarFile)) {
            UmsAdmin umsAdmin = this.getBaseMapper().selectById(id);
            if (Objects.nonNull(umsAdmin)) {
                // 先删除原来的头像
                if (StrUtil.isNotEmpty(umsAdmin.getIcon())) {
                    uploadAvatarFeign.delAvatar(umsAdmin.getIcon());
                }

                // 上传头像
                RespMessUtil<JSONObject> jsonObjectRespMessUtil = uploadAvatarFeign.uploadAvatar(avatarFile);
                System.out.println("==>" + jsonObjectRespMessUtil);
                if (jsonObjectRespMessUtil.getCode() == ConstUtil.STATE_VALUE) {
                    JSONObject data = jsonObjectRespMessUtil.getData();
                    // 更新数据头像
                    this.getBaseMapper().modifyAvatar(id, data.get(RESULT_AVATAR_URL).toString());
                    return jsonObjectRespMessUtil;
                }
            }
        }
        return RespMessUtil.build(CodeStatusEnum.FAILURE);
    }


}
